/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-07-27 08:31:04
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-07-27 08:41:42
 * @FilePath: /yyshort/lib/pages/login/controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:aliplayer_widget/utils/log_util.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:yyshort/common/apis/user_api.dart';
import 'package:yyshort/common/widgets/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:yyshort/pages/personal/personal/controller.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'index.dart';

const List<String> _scopes = <String>[
  'email',
  'https://www.googleapis.com/auth/contacts.readonly',
];

class LoginController extends GetxController {
  LoginController();

  final state = LoginState();

  GoogleSignInUserData? _currentUser;
  bool _isAuthorized = false;
  String _contactText = '';
  String _errorMessage = '';
  Future<void>? _initialization;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    //更新用户信息
    final PersonalController temPonnalCTL = Get.find<PersonalController>();
    temPonnalCTL.onReady();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  // 主视图
  // 模拟 Apple 登录点击事件
  Future<void> signInWithApple() async {
    debugPrint('Sign in with Apple tapped');
    // 这里可添加实际登录逻辑，如调用 Apple 登录相关 SDK 等
    AuthorizationCredentialAppleID credential =
        await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
          nonce: 'example-nonce',
          state: 'example-state',
        );
    logd(credential);
    await UserAPI.thirdLoginWithParams(
      thirdId: credential.userIdentifier!,
      loginType: 2,
      email: credential.email ?? '',
      nickName: (credential.givenName ?? '') + (credential.familyName ?? ''),
    );
    EasyLoading.showSuccess('登录成功'.tr);

    Get.back(result: true);
  }

  // 模拟 Google 登录点击事件
  Future<void> signInWithGoogle() async {
    debugPrint('Sign in with Google tapped');
    // 这里可添加实际登录逻辑，如调用 Google 登录相关 SDK 等
    // GoogleSignInUserData? googleUser = await _signIn();
    // print(googleUser!.email);
    _handleSignIn();
    // _signIn();
  }

  Future<void> _handleSignIn() async {
    try {
      await _ensureInitialized();
      final AuthenticationResults result = await GoogleSignInPlatform.instance
          .authenticate(const AuthenticateParameters());
      _setUser(result.user);

      GoogleSignInUserData? googleUser = result.user;
      if (googleUser != null) {
        //执行三方登录
        await UserAPI.thirdLoginWithParams(
          thirdId: googleUser.id,
          loginType: 1,
          email: googleUser.email ?? '',
          nickName: googleUser.displayName ?? '',
          avatar: googleUser.photoUrl,
        );
        EasyLoading.showSuccess('登录成功'.tr);

        Get.back(result: true);
      } else {
        toastInfo(msg: '登录失败');
      }
    } on GoogleSignInException catch (e) {
      _errorMessage = e.code == GoogleSignInExceptionCode.canceled
          ? ''
          : 'GoogleSignInException ${e.code}: ${e.description}';
    }
  }

  void _setUser(GoogleSignInUserData? user) {
    _currentUser = user;
    if (user != null) {
      // Try getting contacts, in case authorization is already granted.
      _handleGetContact(user);
    }
  }

  Future<void> _handleGetContact(GoogleSignInUserData user) async {
    _contactText = 'Loading contact info...';
    final Map<String, String>? headers = await _getAuthHeaders(user);
    _isAuthorized = headers != null;
    if (headers == null) {
      return;
    }
    final http.Response response = await http.get(
      Uri.parse(
        'https://people.googleapis.com/v1/people/me/connections'
        '?requestMask.includeField=person.names',
      ),
      headers: headers,
    );
    if (response.statusCode != 200) {
      _contactText =
          'People API gave a ${response.statusCode} '
          'response. Check logs for details.';
      print('People API ${response.statusCode} response: ${response.body}');
      return;
    }
    final Map<String, dynamic> data =
        json.decode(response.body) as Map<String, dynamic>;
    final int contactCount =
        (data['connections'] as List<dynamic>?)?.length ?? 0;
    _contactText = '$contactCount contacts found';
  }

  // 模拟 Facebook 登录点击事件
  Future<void> signInWithFacebook() async {
    debugPrint('Sign in with Facebook tapped');
    // 这里可添加实际登录逻辑，如调用 Facebook 登录相关 SDK 等
    final LoginResult result = await FacebookAuth.instance
        .login(); // by default we request the email and the public profile
    // or FacebookAuth.i.login()
    if (result.status == LoginStatus.success) {
      // you are logged
      final AccessToken accessToken = result.accessToken!;
      if (accessToken != null) {
        print("is Logged:::: ${accessToken.toJson()}");
        // now you can call to  FacebookAuth.instance.getUserData();
        final userData = await FacebookAuth.instance.getUserData();
        print("is Logged:::: ");
        if (accessToken != null && userData != null) {
          if (Platform.isIOS) {
            final LimitedToken facebook_userinfo = accessToken as LimitedToken;
            //执行三方登录
            await UserAPI.thirdLoginWithParams(
              thirdId: facebook_userinfo.userId,
              loginType: 3,
              email: facebook_userinfo.userEmail ?? '',
              nickName: facebook_userinfo.userName ?? '',
              avatar: userData['picture']['data']['url'],
            );
          } else if (Platform.isAndroid) {
            final ClassicToken facebook_userinfo = accessToken as ClassicToken;
            //执行三方登录
            await UserAPI.thirdLoginWithParams(
              thirdId: facebook_userinfo.userId,
              loginType: 3,
              email: userData['email'] ?? '',
              nickName: userData['name'] ?? '',
              avatar: userData['picture']['data']['url'],
            );
          }

          EasyLoading.showSuccess('登录成功'.tr);

          Get.back(result: true);
        } else {
          toastInfo(msg: '登录失败');
        }
        // final userData = await FacebookAuth.instance.getUserData(fields: "email,birthday,friends,gender,link");
      }
    } else {
      print(result.status);
      print(result.message);
    }
  }

  ///google signIN
  Future<GoogleSignInUserData?> _signIn() async {
    await _ensureInitialized();
    try {
      final AuthenticationResults? result = await GoogleSignInPlatform.instance
          .attemptLightweightAuthentication(
            const AttemptLightweightAuthenticationParameters(),
          );

      logd(result?.user as Object);
      return result?.user;
    } on GoogleSignInException catch (e) {
      // ignore: unused_local_variable
      String errorMessage = e.code == GoogleSignInExceptionCode.canceled
          ? ''
          : 'GoogleSignInException ${e.code}: ${e.description}';
      loge(errorMessage);
      return null;
    }
  }

  Future<void> _ensureInitialized() {
    return _initialization ??=
        GoogleSignInPlatform.instance.init(
          Platform.isAndroid
              ? InitParameters(
                  clientId: kDebugMode
                      ? '483487025523-n6735phgqkbdpp51psfspgjfqvngfrrt.apps.googleusercontent.com'
                      : '483487025523-c42581esr0gkkv02aa5i62sss8v41a43.apps.googleusercontent.com',
                  //yyshot
                  // '1018842978418-596ha8kjs6cjvq6pv8477s8uv8e8n2b1.apps.googleusercontent.com',
                  // If you need to authenticate to a backend server, specify the server's
                  // OAuth client ID. This is optional.
                  serverClientId:
                      //video-short
                      '483487025523-6ptj3d71rgboc7569bs3pbr1eam48lui.apps.googleusercontent.com',
                  //yyshot
                  // '1018842978418-94dbd5p694oj4c9mj18r1uqeiu49p4ho.apps.googleusercontent.com',
                )
              : InitParameters(
                  clientId:
                      //video-short
                      '483487025523-a9ottviaa6f6asa2gvf21ejoveqsakku.apps.googleusercontent.com',
                  //                     	<key>REVERSED_CLIENT_ID</key>
                  // <string>com.googleusercontent.apps.483487025523-a9ottviaa6f6asa2gvf21ejoveqsakku</string>
                  //yyshot
                  // '1018842978418-47ffqe6r3vg9ejp5mr0hgo3ecdh04kvt.apps.googleusercontent.com',
                ),
        )..catchError((dynamic _) {
          _initialization = null;
        });
  }

  Future<Map<String, String>?> _getAuthHeaders(
    GoogleSignInUserData user,
  ) async {
    final ClientAuthorizationTokenData? tokens = await GoogleSignInPlatform
        .instance
        .clientAuthorizationTokensForScopes(
          ClientAuthorizationTokensForScopesParameters(
            request: AuthorizationRequestDetails(
              scopes: _scopes,
              userId: user.id,
              email: user.email,
              promptIfUnauthorized: false,
            ),
          ),
        );
    if (tokens == null) {
      return null;
    }

    return <String, String>{
      'Authorization': 'Bearer ${tokens.accessToken}',
      // TODO(kevmoo): Use the correct value once it's available.
      // See https://github.com/flutter/flutter/issues/80905
      'X-Goog-AuthUser': '0',
    };
  }
}
